package com.moshang.blog.service.impl;

import com.google.gson.Gson;
import com.moshang.blog.entity.ThirdLogin;
import com.moshang.blog.service.ThirdLoginService;
import com.moshang.blog.service.WeiboService;
import com.moshang.blog.core.utils.HttpUtil;
import com.moshang.blog.core.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: blog
 * @description: ${description}
 * @author: xieweiwei
 * @create: 2018-10-18 10:06
 **/
@Service("weiboService")
public class WeiboServiceImpl implements WeiboService {
    @Autowired
    private ThirdLoginService thirdLoginService;

    private ThirdLogin getInFo(){
        return thirdLoginService.getInFo();
    }

    public static String APPID = "";
    public static String SECRET = "";
    public static String CALLBACK_URL = "http:///weibo/callback";
    /**
     * 发起授权地址
     */
    public static String AUTH_URL = "https://api.weibo.com/oauth2/authorize";
    /**
     *   获取token地址
      */

    public static String TOKEN_URL = "https://api.weibo.com/oauth2/access_token";
    /**
     *  获取用户信息地址
     */

    public static String INFO_URL = "https://api.weibo.com/2/users/show.json";

    /**
     * 获取uid/ass_token
     * @author YangJie [2017年2月22日 下午6:28:49]
     * @param code
     * @return
     */
    @Override
    public Map<String,String> getUid(String code) {
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put("client_id", getInFo().getWeiboAppKey());
        formMap.put("client_secret", getInFo().getWeiboAppSecret());
        formMap.put("grant_type", "authorization_code");
        formMap.put("redirect_uri", getInFo().getWeiboRedictUrl());
        formMap.put("code", code);
        String result = HttpUtil.post(TOKEN_URL, formMap);
        // {"access_token": "ACCESS_TOKEN","expires_in": 1234,"remind_in":"798114","uid":"12341234"}
        Map<String, String> resultMap = JsonUtil.toObject(result, HashMap.class, Map.class, String.class, String.class);
        Map<String,String> map=new HashMap<>();
        map.put("uid",resultMap.get("uid"));
        map.put("token",resultMap.get("access_token"));
        return map;
    }

    /**
     * 获取用户信息
     * @author YangJie [2017年2月22日 下午6:28:49]
     * @param uid
     * @param token
     * @return http://open.weibo.com/wiki/2/users/show
     */
    @Override
    public Map<String, String> getInfo(String uid, String token) {
        String url = new StringBuilder(INFO_URL)
                .append("?access_token=").append(token)
                .append("&uid=").append(uid).toString();
        String result = HttpUtil.get(url);
        Gson gson = new Gson();
        Map<String, String> resultMap= new HashMap<>();
        resultMap = gson.fromJson(result, resultMap.getClass());
        return resultMap;
    }
}
